﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 状态锁
    /// </summary>
    public class LockMa : SingletonMono<LockMa>
    {
        public List<LockState> lockList = new List<LockState>();

        public LockState CreateLock(float time,Action<LockState> onComplete)
        {
            LockState state = new LockState();
            state.onTimeComplete += onComplete;
            state.time = time;
            lockList.Add(state);
            return state;
        }

        public void Update()
        {
            LockState state = null;
            for (int i = 0; i < lockList.Count; i++)
            {
                state = lockList[i];
                if (state.isLock == false)
                    continue;

                state.counter += Time.deltaTime;
                if (state.counter >= state.time)
                {
                    state.counter -= state.time;
                    state.onTimeComplete?.Invoke(state);
                }
            }
        }

        /// <summary>
        /// 计时锁
        /// </summary>
        public class LockState
        {
            public bool isLock;
            public float counter;
            public float time;
            public Action<LockState> onTimeComplete;
        }

        /// <summary>
        /// 只能一次进入,其他进入将无效
        /// </summary>
        public class OnceState
        {
            public bool isLock;
            private Action<object> actionMethod;
            
            public OnceState()
            {
                
            }

            public OnceState(Action<object> onComplete)
            {
                actionMethod = onComplete;
            }

            public void Invoke(object o)
            {
                if (isLock)
                    return;
                isLock = true;
                actionMethod?.Invoke(o);
            }

            public void Clear()
            {
                isLock = false;
            }
        }

        /// <summary>
        /// bool锁,一次进入就会被锁住
        /// </summary>
        public class OnceBoolState
        {
            public bool isActive = false;
            private bool once;

            public bool IsPass()
            {
                if (!isActive)
                    return false;
                
                if (once)
                    return false;

                once = true;
                return true;
            }

            public void UnLock()
            {
                once = false;
                isActive = true;
            }
            public void Lock()
            {
                once = true;
                isActive = false;
            }
        }


    }
}